<script setup>
import { ref, onMounted } from 'vue';
import { usePrintRecords } from '../hooks/usePrintRecords';
import PrintPreviewModal from '../components/PrintPreviewModal.vue';
import { Refresh, Search, RefreshLeft, View } from '@element-plus/icons-vue';

// 使用打印记录相关的hook
const {
  records,
  loading,
  page,
  limit,
  total,
  keyword,
  loadRecords,
  handleSizeChange: handlePageSizeChange,
  changePage,
  searchRecords,
  resetSearch
} = usePrintRecords();

// 初始加载数据
onMounted(() => {
  loadRecords();
});

// 处理页码变化
const handleCurrentChange = (val) => {
  changePage(val);
};

// 处理每页条数变化，直接使用hook中的方法
const handleSizeChange = (val) => {
  handlePageSizeChange(val);
};

// 处理搜索
const handleSearch = () => {
  searchRecords(keyword.value);
};

// 数据格式化函数
const formatCellValue = (value, type = 'string') => {
  // 处理空值
  if (value === null || value === undefined || value === '') {
    return '-';
  }

  // 处理对象类型
  if (typeof value === 'object' && value !== null) {
    try {
      const str = JSON.stringify(value);
      // 限制显示长度
      return str.length > 50 ? str.substring(0, 50) + '...' : str;
    } catch (e) {
      return String(value);
    }
  }

  // 处理日期类型
  if (type === 'date' && typeof value === 'string') {
    try {
      const date = new Date(value);
      if (!isNaN(date.getTime())) {
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        });
      }
    } catch (e) {
      // 如果日期解析失败，返回原始值
    }
  }

  // 默认返回字符串形式
  return String(value);
};

// 刷新记录
const handleRefresh = () => {
  loadRecords();
};

// 预览相关状态
const showPreviewModal = ref(false);
const selectedOrderId = ref(null);

// 处理预览
const handlePreview = async (record) => {
  selectedOrderId.value = record.order_id;
  showPreviewModal.value = true;
};
</script>

<template>
  <div class="print-records">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2>打印记录</h2>
      <el-button type="primary" @click="handleRefresh" :icon="Refresh">
        刷新
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-filter">
      <el-input
        v-model="keyword"
        placeholder="搜索订单号或客户姓名"
        prefix-icon="el-icon-search"
        clearable
        style="width: 300px; margin-right: 10px;"
        @keyup.enter="handleSearch"
      />
      
      <el-button @click="handleSearch" :icon="Search">
        搜索
      </el-button>
      <el-button @click="resetSearch" :icon="RefreshLeft">
        重置
      </el-button>
    </div>

    <!-- 打印记录列表 -->
    <el-table v-loading="loading" :data="records" stripe border style="width: 100%; margin-top: 20px;"
      empty-text="暂无打印记录">
      <el-table-column prop="id" label="记录ID" width="80"></el-table-column>
      <el-table-column prop="order_no" label="订单编号" width="250">
        <template #default="{ row }">
          {{ formatCellValue(row.order_no) }}
        </template>
      </el-table-column>
      <el-table-column prop="customer_name" label="客户姓名" width="250">
        <template #default="{ row }">
          {{ formatCellValue(row.customer_name) }}
        </template>
      </el-table-column>
      <el-table-column prop="print_time" label="打印时间" width="250">
        <template #default="{ row }">
          {{ formatCellValue(row.print_time, 'date') }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            size="small" 
            @click="handlePreview(row)"
            :icon="View"
          >
            预览
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination v-model:current-page="page" v-model:page-size="limit" :page-sizes="[2, 10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </div>

  <!-- 预览模态框 -->
  <PrintPreviewModal
    v-model="showPreviewModal"
    :order-id="selectedOrderId"
    :preview-only="true"
  />
</template>

<style scoped>
.print-records {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.search-filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .search-filter {
    flex-direction: column;
    align-items: stretch;
  }

  .search-filter .el-input {
    width: 100%;
    margin-right: 0;
  }

  .pagination {
    justify-content: center;
  }
}
</style>